package com.malbbmsomanager.print;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.malbbmsomanager.transactions.DM_BBM_InvoiceSalesOrder;
import com.malbbmsomanagerdemo.DM_BBM_InvoiceMenu;
import com.malbbmsomanagerdemo.R;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.MeasureSpec;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class DM_BBM_InvoiceSalesOrder_PrintPreview extends Activity implements
ActionBar.OnNavigationListener {

	private static final String TAG = null;
	// private PBDatabaseAdapter dbHelper;
	private String DBNAME = "dminvoicemanagerbbm.db";
	private SQLiteDatabase mydb;
	private String FORDHED_TABLE = "FOrdHed";
	private String FORDDET_TABLE = "FOrdDet";
	String PrintRefNumber, CurrentRepCode;
	EditText etprintref, etbbmprintdate, etbbmprintcurcode, etbbmprintcustomer,
			etbbmprintaddress, etbbmprintaddressb, etbbmprintaddressc,
			etbbmprinttaxreg, etbbmprintcontact, etbbmprintcontactno,
			etbbmprintremarks, etbbmprintsalesrep, etbbmprintsalreptele,
			etbbmquaotationno,etprintsubtot,etprintgst,etprinttotdiscount,etprintmvrincofgst;
	// action bar
	private ActionBar actionBar;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_sales_order_print_preview);

		actionBar = getActionBar();

		// Hide the action bar title
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(false);

		etprintref = (EditText) findViewById(R.id.etprintref);
		etbbmprintdate = (EditText) findViewById(R.id.etbbmprintdate);
		etbbmprintcustomer = (EditText) findViewById(R.id.etbbmprintcustomer);
		etbbmprintcurcode = (EditText) findViewById(R.id.etbbmprintcurcode);
		etbbmprintaddress = (EditText) findViewById(R.id.etbbmprintaddress);
		etbbmprintaddressb = (EditText) findViewById(R.id.etbbmprintaddressb);
		etbbmprintaddressc = (EditText) findViewById(R.id.etbbmprintaddressc);
		etbbmprintsalesrep = (EditText) findViewById(R.id.etbbmprintsalesrep);
		etbbmprintsalreptele = (EditText) findViewById(R.id.etbbmprintsalreptele);
		etbbmquaotationno = (EditText) findViewById(R.id.etbbmquaotationno);
		etbbmprinttaxreg = (EditText) findViewById(R.id.etbbmprinttaxreg);
		etbbmprintcontact = (EditText) findViewById(R.id.etbbmprintcontact);
		etbbmprintcontactno = (EditText) findViewById(R.id.etbbmprintcontactno);
		etbbmprintremarks = (EditText) findViewById(R.id.etbbmprintremarks);
		
		etprintsubtot = (EditText) findViewById(R.id.etprintsubtot);
		etprintgst = (EditText) findViewById(R.id.etprintgst);
		etprinttotdiscount = (EditText) findViewById(R.id.etprinttotdiscount);
		etprintmvrincofgst = (EditText) findViewById(R.id.etprintmvrincofgst);
		
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			PrintRefNumber = extras.getString("TAGID");
		}
		displayPrintPreviewHeader();
		displayPrintPreviewDetails();

	}

	private void displayPrintPreviewHeader() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curViewHeaderDetails = null;
		String queryViewHeaderDetails;

		try {
			queryViewHeaderDetails = "SELECT RefNo,TxnDate,CurCode,Customer_name,CusAdd1,CusAdd2,CusAdd3,TaxReg,Contact,CusTele,Remarks,RepCode,TotalDis,TotalTax,TotalAmt,InvHedNetTotal FROM FOrdHed Where RefNo = '"
					+ PrintRefNumber + "'";
			curViewHeaderDetails = mydb.rawQuery(queryViewHeaderDetails, null);
		} catch (Exception e) {

		}

		if (curViewHeaderDetails != null) {
			if (curViewHeaderDetails.getCount() > 0) {
				while (curViewHeaderDetails.moveToNext()) {
					String pStrCusAdd1 = "", pStrCusAdd2 = "", pStrCusAdd3 = "";
					String pStrRepTele = "", pStrRepMobil = "";
					String AddressSum = null, RepTeleSum = null;
					String StrRefNo = curViewHeaderDetails.getString(0);
					String StrAppdate = curViewHeaderDetails.getString(1);
					String StrCurCode = curViewHeaderDetails.getString(2);
					String StrCustomer_name = curViewHeaderDetails.getString(3);
					String StrCusAdd1 = curViewHeaderDetails.getString(4);
					String StrCusAdd2 = curViewHeaderDetails.getString(5);
					String StrCusAdd3 = curViewHeaderDetails.getString(6);
					String StrTaxReg = curViewHeaderDetails.getString(7);
					String StrContact = curViewHeaderDetails.getString(8);
					String StrCusTele = curViewHeaderDetails.getString(9);
					String StrRemarks = curViewHeaderDetails.getString(10);
					CurrentRepCode = curViewHeaderDetails.getString(11);
					String StrTotalDis = curViewHeaderDetails.getString(12);
					String StrTotalTax = curViewHeaderDetails.getString(13);
					String StrTotalAmt = curViewHeaderDetails.getString(14);
					String StrHedNetTotal = curViewHeaderDetails.getString(15);
					
					
					
					/*
					 * String StrRepName = curViewHeaderDetails.getString(13);
					 * String StrRepTele = curViewHeaderDetails.getString(14);
					 * String StrRepMobil = curViewHeaderDetails.getString(15);
					 */
					Log.v(TAG, "CurrentRepCode  :" + CurrentRepCode);
					try {

						if (StrCusAdd1.length() != 0) {
							pStrCusAdd1 = StrCusAdd1;
						}
						if (StrCusAdd1.length() != 0) {
							pStrCusAdd2 = StrCusAdd2;
						}
						if (StrCusAdd3.length() != 0) {
							pStrCusAdd3 = StrCusAdd3;
						}
						/*
						 * if(StrRepTele.length()!=0){ pStrRepTele = StrRepTele;
						 * } if(StrRepMobil.length()!=0){ pStrRepMobil =
						 * StrRepMobil; }
						 */

						// RepTeleSum = pStrRepTele + "," + pStrRepMobil;
					} catch (Exception e) {
						Log.v(TAG, "Exception  :" + e);
					}
					
					String[] separated = StrAppdate.split(" ");
					StrAppdate = separated[0]; // this will contain Date Part
					
					etprintref.setText(": " + StrRefNo);
					etbbmprintdate.setText(": " + StrAppdate);
					etbbmprintcurcode.setText(": " + StrCurCode);
					etbbmprintcustomer.setText(": " + StrCustomer_name);
					etbbmprintaddress.setText(": " + pStrCusAdd1);
					etbbmprintaddressb.setText(": " + pStrCusAdd2);
					etbbmprintaddressc.setText(": " + pStrCusAdd3);
					etbbmprinttaxreg.setText(": " + StrTaxReg);
					etbbmprintcontact.setText(": " + StrContact);
					etbbmprintcontactno.setText(": " + StrCusTele);
					etbbmprintremarks.setText(": " + StrRemarks);
					
					BigDecimal StrHedNetTotalVal = new BigDecimal(StrHedNetTotal.replaceAll("[,]", ""));
					BigDecimal StrTotalTaxVal = new BigDecimal(StrTotalTax.replaceAll("[,]", ""));
					BigDecimal PrintSubTotVal = StrHedNetTotalVal.subtract(StrTotalTaxVal);
					PrintSubTotVal = PrintSubTotVal.setScale(2, BigDecimal.ROUND_HALF_DOWN);
					
					etprintsubtot.setText(""+PrintSubTotVal);
					etprintgst.setText(StrTotalTax);
					etprinttotdiscount.setText(StrTotalDis);
					etprintmvrincofgst.setText(StrHedNetTotal);

				}
			} else {
				Log.v(TAG, "NO ITEMS");
			}
		}
		curViewHeaderDetails.close();
		mydb.close();
		displayRepDetails();
	}

	private void displayRepDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curViewRepDetails = null;
		String queryViewRepDetails;
		Log.v(TAG, "displayRepDetails");
		try {
			CurrentRepCode = CurrentRepCode.toUpperCase();
			queryViewRepDetails = "SELECT RepCode,RepName,RepTele FROM fSalRep Where RepCode ='"
					+ CurrentRepCode + "'";
			curViewRepDetails = mydb.rawQuery(queryViewRepDetails, null);
		} catch (Exception e) {

		}
		if (curViewRepDetails != null) {
			if (curViewRepDetails.getCount() > 0) {
				while (curViewRepDetails.moveToNext()) {
					String RepCode = curViewRepDetails.getString(0);
					String RepName = curViewRepDetails.getString(1);
					String RepTele = curViewRepDetails.getString(2);
					if (RepTele.trim().length() != 0) {
						etbbmprintsalreptele.setText(": " + RepTele);
					}
					etbbmprintsalesrep.setText(": " + RepName);
					Log.v(TAG, "RepCode:" + RepCode);
				}
			} else {
				Log.v(TAG, "NOT Found to displayRepDetails");
			}
		}
		curViewRepDetails.close();
		mydb.close();
	}

	private void displayPrintPreviewDetails() {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dminvoiceitemsdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2", "coldes_3",
				"coldes_4", "coldes_5", "coldes_6", "coldes_7", "coldes_8",
				"coldes_9" };
		int[] totrdes = new int[] { R.id.grid_value_a, R.id.grid_value_b,
				R.id.grid_value_c, R.id.grid_value_d, R.id.grid_value_e,
				R.id.grid_value_f, R.id.grid_value_g, R.id.grid_value_h,
				R.id.grid_value_i };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curViewSODetails = null;
		String queryViewSODetails;

		try {
			queryViewSODetails = "SELECT SeqNo,Itemcode,ItemName,Packing,Qty,freeqty,totordval,RefNo,TaxAmt,OrSellPrice FROM FOrdDet Where RefNo = '"
					+ PrintRefNumber + "'";
			curViewSODetails = mydb.rawQuery(queryViewSODetails, null);
		} catch (Exception e) {

		}

		if (curViewSODetails != null) {
			if (curViewSODetails.getCount() > 0) {
				while (curViewSODetails.moveToNext()) {
					String record_0 = curViewSODetails.getString(0);// SeqNo
					String record_1 = curViewSODetails.getString(1);// Itemcode
					String record_2 = curViewSODetails.getString(2);// ItemName
					String record_3 = curViewSODetails.getString(3);// Quopacking
					String record_4 = curViewSODetails.getString(4);// Qty
					String record_5 = curViewSODetails.getString(5);// freeqty
					String record_6 = curViewSODetails.getString(6);// totordval
					String record_7 = curViewSODetails.getString(8);// TaxAmt
					String record_8 = curViewSODetails.getString(9);// SellPrice

					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", record_0);
					maptrdes.put("coldes_2", record_1);
					maptrdes.put("coldes_3", record_2);
					maptrdes.put("coldes_4", record_3);
					maptrdes.put("coldes_5", record_4);
					maptrdes.put("coldes_6", record_5);
					maptrdes.put("coldes_7", record_7);
					maptrdes.put("coldes_8", record_8);
					maptrdes.put("coldes_9", record_6);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes,
						R.layout.dm_bbm_sales_order_print_preview_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
				
				
				ListAdapter listAdapter = lvtypedes.getAdapter();
				if (listAdapter == null) {
					// pre-condition
					return;
				}

				int totalHeight = 0;
				int desiredWidth = MeasureSpec.makeMeasureSpec(lvtypedes.getWidth(),
						MeasureSpec.AT_MOST);
				for (int i = 0; i < listAdapter.getCount(); i++) {
					View listItem = listAdapter.getView(i, null, lvtypedes);
					listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
					totalHeight += listItem.getMeasuredHeight();
				}

				ViewGroup.LayoutParams params = lvtypedes.getLayoutParams();
				params.height = totalHeight
						+ (lvtypedes.getDividerHeight() * (listAdapter.getCount() - 1));
				lvtypedes.setLayoutParams(params);
				lvtypedes.requestLayout();
			}
		}
		curViewSODetails.close();
		mydb.close();
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
		
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_search:
			// search action
			return true;
		case R.id.action_location_found:
			// location found
			LocationFound();
			return true;
		case R.id.action_refresh:
			// refresh
			/*
			 * refreshMenuItem = item; // load the data from server new
			 * SyncData().execute();
			 */
			return true;
		case R.id.action_help:
			// help action
			return true;
		case R.id.action_check_updates:
			// check for updates action
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void LocationFound() {
		// TODO Auto-generated method stub
		Intent i = new Intent(DM_BBM_InvoiceSalesOrder_PrintPreview.this,
				DM_BBM_InvoiceMenu.class);
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(i);
		finish();
		return;
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_actions, menu);
		return true;
	}

}
